package logic

import (
	"context"
	"github.com/Masterminds/squirrel"

	"t-go-zero/service/user/rpc/internal/svc"
	"t-go-zero/service/user/rpc/userclient"

	"github.com/zeromicro/go-zero/core/logx"
)

type ARoleListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewARoleListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ARoleListLogic {
	return &ARoleListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *ARoleListLogic) ARoleList(in *userclient.ARoleListReq) (*userclient.ARoleListResp, error) {
	whereBuilder := l.svcCtx.ARoleModel.RowBuilder()

	whereBuilder = whereBuilder.OrderBy("created_at DESC, id DESC")

	// 角色名称
	if len(in.Name) > 0 {
		whereBuilder = whereBuilder.Where(squirrel.Like{
			"name ": "%" + in.Name + "%",
		})
	}
	// 备注
	if len(in.Remark) > 0 {
		whereBuilder = whereBuilder.Where(squirrel.Eq{
			"remark ": in.Remark,
		})
	}

	all, err := l.svcCtx.ARoleModel.FindList(l.ctx, whereBuilder, in.Current, in.PageSize)
	if err != nil {
		return nil, err
	}

	countBuilder := l.svcCtx.ARoleModel.CountBuilder("id")

	// 角色名称
	if len(in.Name) > 0 {
		countBuilder = countBuilder.Where(squirrel.Like{
			"name ": "%" + in.Name + "%",
		})
	}
	// 备注
	if len(in.Remark) > 0 {
		countBuilder = countBuilder.Where(squirrel.Like{
			"remark ": "%" + in.Remark + "%",
		})
	}
	count, err := l.svcCtx.ARoleModel.FindCount(l.ctx, countBuilder)
	if err != nil {
		return nil, err
	}

	var list []*userclient.ARoleListData
	for _, item := range all {
		list = append(list, &userclient.ARoleListData{
			Id:          item.Id,                    //角色ID
			Name:        item.Name,                  //角色名称
			Remark:      item.Remark.String,         //备注
			CreatedName: item.CreatedName,           //创建人
			CreatedAt:   item.CreatedAt.UnixMilli(), //创建时间
		})
	}

	return &userclient.ARoleListResp{
		Total: count,
		List:  list,
	}, nil
}
